/**
 * Created by tdzl2003 on 12/18/16.
 */

import React, {Component, PropTypes} from 'react';
import {
    AsyncStorage,
    Image,
    LayoutAnimation,
    NativeModules,
    StyleSheet,
    Text,
    TextInput,
    View,
    Button,
    SectionList,
    TouchableOpacity,
    ScrollView,
    Platform
} from 'react-native';
import Dimensions from 'Dimensions';
import CheckBox from 'react-native-checkbox';

import Toast from "react-native-simple-toast";
import AppService from "../service/AppService";
import DistributeSucc from './DistributeSucc';
import User from "../contract/suggest/domain/User";
import RString from '../language/RString';

const check_Img = require('./img/checked.png');
const uncheck_Img = require('./img/uncheck_Img.png');

const styles = StyleSheet.create({
    body: {
        // height: Dimensions.get('window').height,
        flex: 1,
        backgroundColor: '#fff',
        position: 'relative'
    },
    commonHeader:{
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        backgroundColor:'#333238',
        flexDirection:'row',
        justifyContent:'center',
        position:'relative'
    },
    back:{
        width:30,
        position:'absolute',
        left:20,
        top:0,
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        justifyContent:'center'
    },
    toIndex:{
        width:30,
        position:'absolute',
        left:70,
        top:0,
        height: Platform.OS === 'android'? 50 : 60,
        paddingTop: Platform.OS === 'ios'? 20 : 0,
        justifyContent:'center'
    },
    searchBox: {
        height: 30,
        flexDirection: 'row',
        flex: 1,
        borderRadius: 5,
        backgroundColor: 'white',
        alignItems: 'center',
        marginTop: 10,
        marginBottom: 10,
        marginLeft: 10,
        marginRight: 10,
    },
    searchIcon: {
        marginLeft: 10
    },
    searchText: {
        width: 300,
        marginLeft: 5
    },
    bottomBox: {
        width: Dimensions.get('window').width,
        height: 60,
        backgroundColor: '#E8E8EC',
        position: 'absolute',
        bottom: 0,
        paddingTop: 15,
        paddingBottom: 15,
        paddingLeft: 15,
        flexDirection: 'row',
    },
    bottomBtn: {
        width: 100,
        borderRadius: 5,
        paddingLeft: 7,
        paddingTop: 6,
        paddingBottom: 7,
        backgroundColor: '#3399FF',
        flexDirection: 'row',
        justifyContent: 'center'
    },
    mainList:{
        flex:1,
        marginBottom:50
    },
    mainItem:{
        width:'90%',
        height:44,
        alignSelf:'center',
        flexDirection:'row',
        borderBottomWidth:1,
        borderBottomColor:'#eee'
    },
    item:{
        flex:8,
        paddingTop:12,
        flexDirection:'row'
    },
    itemIcon:{
        flex:1,
        paddingTop:10
    }
});

const onButtonPress = () => {
    Alert.alert('Button has been pressed!');
};


export default class Distribute extends Component {
    constructor(props) {
        super(props);
        this.state = {
            title:RString('assign_person'),
            text: 'Useless Placeholder',
            responsibleList:[],
            whichResponsible:'',
            keyWord:'',
            responsibleId:'',
            userList:[],
            responsibleNameList:'',
        };
    }

    goBack = () => {
        const{navigator} = this.props;
        if(navigator){
            navigator.pop();
        }
    };
    doClose = () => {
        NativeModules.system.navTo("BACK");
    };

    _onPress = () => {
        console.warn(this.props.navigation.navigate("option"))
    };

    searchDistribute = (text) =>{
        let  _this=this;
        this.setState({
            keyWord:text
        });
        if(this.state.keyWord !== this.state.whichResponsible) {
            this.setState({
                whichResponsible:0
            });
        };
        if(text) {
            AppService.findSuggestPersonList({keyword:text,tenantId:global.tenantId}).then(data => {
                if (!!data.errors === true && !!data.errors.length > 0) {
                    Toast.show(data.errors[0].message);
                } else {
                    let itemList=data.result||[];
                    if(itemList.length == 0){
                        Toast.show(RString('search_result'));
                        _this.setState({
                            responsibleList:[]
                        });
                    }else{
                        for(let i=0;i<itemList.length;i++){
                            let item=itemList[i];
                            item.value=false;
                        }
                        _this.setState({
                            responsibleList:itemList
                        });
                    }
                }
            });
        } else {
            _this.setState({
                responsibleList:[]
            });
        }
    };

    selectResponsible(idx,id,name){
       if(this.state.responsibleList[idx].value==true){
           let userListTemp=[];
           this.state.responsibleList[idx].value=false;
           for(let i=0;i<this.state.userList.length;i++){
              if(this.state.userList[i].id !=id){
              userListTemp.push(this.state.userList[i]);
              }
           }
         this.setState({
           userList:userListTemp,
         },function(){
          let resName='';
          for(let j=0;j<this.state.userList.length;j++){
            if(resName==''){
             resName =this.state.userList[j].name;
            }else {
             resName =resName+','+this.state.userList[j].name;
            }

          }
         this.setState({
              whichResponsible:resName,
          });
         });
        }else if(this.state.responsibleList[idx].value==false){
         this.state.responsibleList[idx].value=true;
                  let user=new User();
                  user.setId(id);
                  user.setName(name);
                  var items = this.state.userList;
                  items.push(user);
                  this.setState({
                  userList:items,
                  });
            let resName='';
           for(let j=0;j<this.state.userList.length;j++){
             if(resName==''){
                resName =this.state.userList[j].name;
               }else {
                resName =resName+','+this.state.userList[j].name;
               }
           }
          this.setState({
               whichResponsible:resName,
           });
        }
       this.setState({
                keyWord:name,
                responsibleId:id
       });
    }

    renderResponsible = (v, i) =>{
        return (
            <View style={styles.mainItem} key={i}>
                <View style={styles.item}>
                    <Text style={{fontSize:18,color:'#3399FF'}}>{v.name}</Text>
                </View>
                <View style={styles.itemIcon}>
                    <CheckBox label='' underlayColor="#fff" checked={v.value} uncheckedImage={uncheck_Img} checkedImage={check_Img} onChange={() => this.selectResponsible(i,v.id,v.name)}/>
                </View>
            </View>
        )
    };

    doDistribute = () => {
       for(let i=0;i<this.state.responsibleList.length;i++){
        if(this.state.responsibleList[i].value==true){
          Toast.show(this.state.responsibleList[i].name);
        }
       }
       if(this.state.whichResponsible){
            const{navigator} = this.props;
            let responsible={
                id:this.props.id,
                dealId:this.state.responsibleId,
                dealName:this.state.whichResponsible,
                userList:this.state.userList
            };
            AppService.updatePrincipal(responsible).then(data => {
                if (!!data.errors === true && !!data.errors.length > 0) {
                    Toast.show(data.errors[0].message);
                } else {
                    if(navigator){
                        navigator.push({
                            name: "DistributeSucc",
                            component:DistributeSucc,
                            params :{
                                responsible:this.state.whichResponsible
                            }
                        });
                    }
                }
                let vm = {
                    businessId: this.props.id,
                    businessType: 'DOCK',
                    anonymous: false,
                    userId: global.userId,
                    content: global.userName + RString('responsible') + this.state.whichResponsible
                };
                AppService.createCommentRecord(vm).then(data => {
                    if (!!data.errors === true && !!data.errors.length > 0) {
                        Toast.show(data.errors[0].message);
                    } else {

                    }
                });
            });
        }else{
            Toast.show(RString('input_distributor'));
        }
    };

    render() {
        return (
            <View style={styles.body}>
                <View style={styles.commonHeader}>
                    <TouchableOpacity onPress={this.goBack.bind(this)} style={styles.back}>
                        <Image source={require('./img/leftArrow.png')} />
                    </TouchableOpacity>
                    <TouchableOpacity onPress={this.doClose.bind(this)} style={styles.toIndex}>
                        <Image source={require('./img/chahao.png')}/>
                    </TouchableOpacity>
                    <View style={{ justifyContent:'center' }}>
                        <Text style={{ color:'#fff',fontSize:16 }}>{this.state.title}</Text>
                    </View>
                </View>
                <View style={{height: 60, backgroundColor: '#E8E8EC'}}>
                    <View style={styles.searchBox}>
                        <Image style={styles.searchIcon} source={require('./img/searchIcon.png')}/>
                        <TextInput
                            style={styles.searchText}
                            placeholder={RString('initials')}
                            placeholderTextColor={'#ccc'}
                            underlineColorAndroid='transparent'
                            onChangeText={this.searchDistribute}
                            value={this.state.keyWord}
                        />
                    </View>
                </View>
                <ScrollView style={styles.mainList}>
                    {this.state.responsibleList.map((v, i) => this.renderResponsible(v, i))}
                    <View style={{flex:1,height:44}}></View>
                </ScrollView>
                <View style={styles.bottomBox}>
                    <View style={{flex: 1, flexDirection: 'row', justifyContent: 'flex-start'}}>
                        <View style={{justifyContent: 'center'}}>
                            <Text style={{color: '#aaa'}}>{RString('already_select')}：{this.state.whichResponsible?this.state.whichResponsible:0}</Text>
                        </View>
                    </View>
                    <View style={{flex: 1, flexDirection: 'row', justifyContent: 'flex-end', marginRight: 10}}>
                        <TouchableOpacity style={styles.bottomBtn} onPress={this.doDistribute.bind(this)}>
                            <Text style={{ color:'#fff' }}>{RString('assign_ta')}</Text>
                        </TouchableOpacity>
                    </View>
                </View>

            </View>
        );
    }
}
